﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.IO;
using AlocaProfeV2.Modelos;

namespace AlocaProfeV2.Dao
{
    public class DisciplinaDao
    {
        String xml_path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "xml/disciplina.xml");

        public void cadastraDisciplina(Disciplina disciplina)
        {

            XDocument xmldisciplina = XDocument.Load(xml_path);

            //Descobrindo o ultimo id e definindo o id a ser criado
            Int32 ultimo_id = Convert.ToInt32(xmldisciplina.Descendants("Disciplinas").Elements("Disciplina").Last().Attribute("id").Value);
            ultimo_id += 1;

            xmldisciplina.Element("Disciplinas").Add(
                new XElement("Disciplina",
                    new XAttribute("id", ultimo_id),
                    new XElement("Nome", disciplina.Nome),
                    new XElement("Sigla", disciplina.Sigla),
                    new XElement("CodigoTurma", disciplina.CodigoTurma),
                    new XElement("Semestre", disciplina.Semestre),
                    new XElement("Area"),
                    new XElement("Periodo", disciplina.Periodo), 
                    new XElement("DiaSemana", disciplina.DiaSemana),
                    new XElement("Alocada", false)
                    )
            );
            xmldisciplina.Save(xml_path);
        }

        public List<Disciplina> listaDisciplina()
        {
            XDocument xmldisciplina = XDocument.Load(xml_path);
            List<Disciplina> disciplinas = new List<Disciplina>();

            var data = from item in xmldisciplina.Descendants("Disciplina")
                       select new
                       {
                           id = item.Attribute("id").Value,
                           sigla = item.Element("Sigla").Value,
                           nome = item.Element("Nome").Value,
                           semestre = item.Element("Semestre").Value,
                           codigoTurma = item.Element("CodigoTurma").Value,
                           periodo = item.Element("Periodo").Value,
                           diaSemana = item.Element("DiaSemana").Value,
                           alocada = item.Element("Alocada").Value
                       };

            foreach (var disciplina in data)
            {
                Disciplina objDisciplina = new Disciplina(Convert.ToInt32(disciplina.id), disciplina.sigla, disciplina.nome, Convert.ToInt32(disciplina.semestre), disciplina.codigoTurma, disciplina.periodo, disciplina.diaSemana, Boolean.Parse(disciplina.alocada));
                disciplinas.Add(objDisciplina);
            }
            return disciplinas;
        }


    }
}